#include "./elock.h"
#include "../device/gpio.h"
#include "../driver/analog.h"
#include "../driver/sensor.h"

namespace driver {

using namespace device;
using namespace utils;

ELock elock;

enum class Dir {
    OPEN = 0,
    CLOSE = 1,
    BRAKE = 2,
};

static void set_dir(Dir dir);

using K1 = PB<7>;
using K2 = PB<8>;
using K3 = PB<9>;
using K4 = PB<12>;
using K5 = PB<13>;

void ELock::init() {
    RCU_APB2EN |= RCU_APB2EN_PBEN;
    config_pp_output<K1, K2, K3, K4, K5>();
    set_dir(Dir::BRAKE);
}


Error ELock::open() {
    set_dir(Dir::CLOSE);
    K1::set();

    osDelay(500);

    set_dir(Dir::BRAKE);
    K1::clr();

    if (sensor.is_elock_close()) {
        return ec::ELOCK_FAIL;
    }
    return ec::OK;
}

static void set_dir(Dir dir) {
    switch (dir) {
        case Dir::CLOSE: 
            K4::set();
            K5::clr();
        break;

        case Dir::OPEN:
            K4::clr();
            K5::set();
        break;

        case Dir::BRAKE:
            K4::clr();
            K5::clr();
        break;
		
		default: break;
    }
}

}
